# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/7/16
import os
import random
from time import sleep

import requests
from submodules.common.lib.log_ import get_logger

from submodules.common.lib.datetime_ import get_timestamp

from submodules.common.lib import local_paths

from submodules.common.lib.json_ import (
    loads_jsonp,
    json_file_to_dict,
    dict_to_json_file,
)

logger = get_logger()


def trans_code_upper_to_lower(ths_code_upper):
    """
    SH512780
    sh_512780
    """
    if len(ths_code_upper) == 8:
        ths_code_lower = ths_code_upper[:2].lower() + "_" + ths_code_upper[2:]
    else:
        # 美股ETF
        ths_code_lower = "169" + "_" + ths_code_upper
    return ths_code_lower


def get_candles_data(ths_code):
    """
    https://m.10jqka.com.cn/stockpage/hs_1A0001
    https://d.10jqka.com.cn/v6/line/hs_1A0001/01/last360.js
    https://d.10jqka.com.cn/v6/line/hs_1A0001/01/today.js

    :param tx_code:
    :return:
    """

    data_dir = os.path.join(local_paths.project_tmp_path, "data")
    if os.path.exists(data_dir):
        pass
    else:
        os.mkdir(data_dir)
    # date_str = get_timestamp()[:8]
    date_str = get_timestamp()[:10]  # 取到小时

    data_path = os.path.join(data_dir, f"{date_str}_{ths_code}.json")
    if os.path.exists(data_path):
        try:
            res = json_file_to_dict(data_path)
            logger.info(f"use local data, data_name:{ths_code}")
            return res
        except Exception as e:
            logger.error(f"data_path:{data_path}")
            logger.error(repr(e))

    params = {}

    # 伪装成浏览器
    headers = {
        "Connection": "keep-alive",
        "Cache-Control": "max-age=0",
        "sec-ch-ua": '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
        "sec-ch-ua-mobile": "?0",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-User": "?1",
        "Sec-Fetch-Dest": "document",
        # 'Referer': 'https://bj.ke.com/',
        "Accept-Language": "zh-CN,zh;q=0.9",
    }

    url1 = f"https://d.10jqka.com.cn/v6/line/{ths_code}/01/last360.js"
    candles_data = []
    for i in range(600):
        try:
            res = requests.get(url=url1, headers=headers, params=params, verify=False)
            logger.info(res.url)
            data = loads_jsonp(res.text)["data"]
            logger.info(f"ths_data:{data}")
            break
        except:
            sleep(random.uniform(3, 5))

    list_tmp = data.split(";")
    for i in range(len(list_tmp)):
        data2 = list_tmp[i].strip("").split(",")
        try:
            trade_date = data2[0]
            open = float(data2[1])
            high = float(data2[2])
            low = float(data2[3])
            close = float(data2[4])
            vol = data2[5]
        except Exception as e:
            logger.error(repr(e))
            continue

        amount = 0
        # candles_data.append([trade_date, open, high, low, close, vol, amount, gains_percent, amplitude_percent])
        candles_data.append([trade_date, open, high, low, close, vol, amount])

    candles_data.reverse()

    url2 = f"https://d.10jqka.com.cn/v6/line/{ths_code}/01/today.js"
    for i in range(600):
        try:
            res = requests.get(url=url2, headers=headers, params=params, verify=False)
            logger.info(res.url)
            data = loads_jsonp(res.text)[f"{ths_code}"]
            logger.info(f"ths_data:{data}")
            break
        except:
            sleep(1)

    try:
        trade_date = data["1"]
        open = float(data["7"])
        high = float(data["8"])
        low = float(data["9"])
        close = float(data["11"])
        vol = float(data["13"])
    except Exception as e:
        logger.error(repr(e))
        return candles_data
    amount = 0
    today_data = [trade_date, open, high, low, close, vol, amount]

    if candles_data[0][0] == today_data[0]:
        candles_data = [today_data] + candles_data[1:]  # 360接口的最后一天数据有问题，删除360接口的最后一天数据
    else:
        candles_data = [today_data] + candles_data

    # 添加涨幅
    for i in range(len(candles_data) - 1):
        close_yesterday = candles_data[i + 1][4]
        close = candles_data[i][4]
        gains_percent = (close - close_yesterday) / close_yesterday * 100
        candles_data[i].append(gains_percent)
    dict_to_json_file(candles_data, data_path)
    return candles_data


if __name__ == "__main__":
    def test_get_candles_data():
        ths_code = "hs_1A0001"
        ths_code = "hs_512480"
        ths_code = "sz_59865"
        ths_code = "sz_159613"
        ths_code = "sh_512980"
        res = get_candles_data(ths_code)
        print(res)


    def test_trans_code_upper_to_lower():
        ths_code_upper = "SH512780"

        res = trans_code_upper_to_lower(ths_code_upper)
        print(res)
        ths_code_lower = "sh_512780"


    test_get_candles_data()
